package com.example.gobang.config;

import com.example.gobang.controller.GameController;
import com.example.gobang.controller.MatchController;
import com.example.gobang.controller.TestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * Description:
 * Date: 2024-09-03
 * Time: 20:34
 */
@Configuration
@EnableWebSocket  //让 Spring 框架可以识别出这是配置 websocket 的类，再基于这个类找到 TestApi，进而处理 websocket 相关的请求
public class WebSocketConfig implements WebSocketConfigurer {
    @Autowired
    private TestController testController;

    @Autowired
    private MatchController matchController;

    @Autowired
    private GameController gameController;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 注册 testController 实例
        registry.addHandler(testController,"/test"); //客户端连接这个路径时  可以调用 TestApi 的接口
        // 注册 matchController 实例
        // 添加拦截器是为了把前面准备好的 HttpSession 弄到 WebSocket 的 Session 中（WebSocket 也有 session）
        registry.addHandler(matchController,"/findMatch")
                .addInterceptors(new HttpSessionHandshakeInterceptor());
        registry.addHandler(gameController,"/game")
                .addInterceptors(new HttpSessionHandshakeInterceptor());
    }
}
